package it.antonio.ilpizze.func;

import java.util.Iterator;
import java.util.NoSuchElementException;

public abstract class ComputeIterator<T> implements Iterator<T> {
	private State state = State.Ready;
	private T current;

	protected abstract T computeNext();

	protected final T finished() {
		state = State.Finished;
		return null;
	}

	public final boolean hasNext() {
		if (state == State.Ready) {
			current = computeNext();
			if (state == State.Finished) {
				return false;
			}
			state = State.Loaded;
		}
		return state != State.Finished;

	}

	public final T next() {
		if (hasNext()) {
			return pop();
		}
		throw new NoSuchElementException();
	}

	private T pop() {
		state = State.Ready;
		return current;
	}

	@Override
	public final void remove() {
		throw new UnsupportedOperationException();
	}

	private enum State {
		Ready, Loaded, Finished;
	}
}